package de.koller.reason.gui.component.button;

import de.koller.reason.gui.GUIRoot;
import de.koller.reason.gui.component.RPanel;
import de.koller.reason.gui.component.mo.GlowMode;
import de.koller.reason.gui.renderObj.IRenderObject;
import de.koller.reason.gui.renderObj.IRenderPosition;
import de.koller.reason.gui.textureObj.IPart;
import java.util.HashSet;
import java.util.Set;

public class RButton extends RPanel implements IButton {
	
	private final Set<IButtonListener> listeners = new HashSet<>();
	private final GlowMode glowMode;
	
	private ButtonStatus status = ButtonStatus.MouseLess;

	public RButton( IPart visual ) {
		this( visual, GlowMode.MouseOver );
	}
	
	public RButton( IPart visual, GlowMode glowMode ) {
		super( visual );
		this.glowMode = glowMode;
	}

	@Override
	public void addTo( GUIRoot gui, Set<IRenderObject> renderSet ) {
		super.addTo( gui, renderSet );
		if( !gui.buttons.add( this ) )
			throw new IllegalArgumentException( "can't add button!" );
		
		if( glowMode == GlowMode.Always )
			gui.renderRoot.glower.letGlow( this );
	}
	
	@Override
	public void removeFrom( GUIRoot gui ) {
		super.removeFrom( gui );
		if(	!gui.buttons.remove( this ) )
			throw new IllegalArgumentException( "can't remove button!" );
		
		if( glowMode == GlowMode.Always )
			gui.renderRoot.glower.stopGlow( this );
	}
	
	private void setStatus( ButtonStatus status ) {
		switch( status ) {
			case MouseLess:
				if( glowMode == GlowMode.MouseOver )
					gui.renderRoot.glower.stopGlow( this );
				break;
			case MouseOver:
				if( glowMode == GlowMode.MouseOver )
					gui.renderRoot.glower.letGlow( this );
				break;
			case MouseDown:

				break;
			default:
				throw new IllegalArgumentException( "dont't know: " + this.status );
		}
		
		this.status = status;
	}

	@Override
	public IRenderPosition getDimension() {
		return this;
	}
	
	@Override
	public void buttonEvent( ButtonEvent e ) {
		if( e.buttonStatus == ButtonStatus.MouseReleased )
			setStatus( ButtonStatus.MouseOver );
		else
			setStatus( e.buttonStatus );
		
		for( IButtonListener l : listeners )
			l.eventOccured( e );
	}
	
	public void addButtonListener( IButtonListener listener ) {
		if( !listeners.add( listener ) )
			throw new IllegalArgumentException( "can't add listener!" );
	}
	
	public void removeButtonListener( IButtonListener listener ) {
		if( !listeners.remove( listener ) )
			throw new IllegalArgumentException( "can't remove listener!" );
	}
	
}
